using Microsoft.Extensions.Options;
using PHMEE.VibrationDataGenerator.Components;
using PHMEE.VibrationDataGenerator.Data;
using PHMEE.VibrationDataGenerator.Services;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Compact;

Log.Logger = new LoggerConfiguration()
#if DEBUG
    .MinimumLevel.Debug()
#else
    .MinimumLevel.Information()
#endif
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.Async(c => c.File(new CompactJsonFormatter(), "Logs/logs-.txt", rollingInterval: RollingInterval.Day))
    .WriteTo.Async(c => c.Console())
    .CreateLogger();

try
{
    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.
    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents();

    // 添加内存缓存服务
    builder.Services.AddMemoryCache();

    builder.Services.AddSingleton<VibDataCacheService>();
    builder.Services.AddSingleton<ChannelConfigRepository>();
    builder.Services.AddSingleton<TaskConfigRepository>();
    builder.Services.AddSingleton<TaskManagementService>();
    builder.Services.AddSingleton<WeiLiVibDataFilesService>();

    builder.Services.AddTransient<VibDataGenerateDynamicTaskJob>();
    builder.Services.AddSingleton<IJobFactory, VibDataGeneratorTaskJobFactory>();
    builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
    builder.Services.AddSingleton<TaskManager>();
    builder.Services.AddOptions<MqttSettings>().BindConfiguration("MqttSettings");

    builder.Services.AddSingleton<MqttClientPool>(sp =>
    {
        int maxPoolSize = 10;
        var mqttSettings = sp.GetRequiredService<IOptions<MqttSettings>>();
        var logger = sp.GetRequiredService<ILogger<MqttClientPool>>();
        return new MqttClientPool(maxPoolSize, mqttSettings, logger);
    });

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error", createScopeForErrors: true);
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    app.UseStaticFiles();
    app.UseAntiforgery();

    app.MapRazorComponents<App>()
        .AddInteractiveServerRenderMode();

    // 获取 VibDataCacheService 实例并加载数据
    app.Logger.LogInformation("正在加载振动数据...");
    var vibDataCacheService = app.Services.GetRequiredService<VibDataCacheService>();
    vibDataCacheService.LoadData();
    app.Logger.LogInformation("振动数据加载完成。");

    // 启动任务管理器
    app.Logger.LogInformation("正在启动任务管理器...");
    var taskManager = app.Services.GetRequiredService<TaskManager>();
    taskManager.StartAsync().GetAwaiter().GetResult();
    app.Logger.LogInformation("任务管理器已启动。");

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "server terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}